from tkinter import Image
from PIL import Image
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from time import sleep
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pytest
from Wzx.wzx9_23.cookies.dama import Dama


@pytest.fixture(scope='function')
def driver():
    driver = webdriver.Edge()
    driver.get('http://10.59.9.14:7003/')
    driver.maximize_window()
    yield driver
    driver.quit()

def test_A3mall(driver):
    #点击登录
    driver.find_element(By.XPATH,'//a[@href="/home/login.html"]').click()
    #断言会员登录
    dy1 = driver.find_element(By.CLASS_NAME,'reg-new').text
    print(dy1)
    assert '会员登录' == dy1
    #输入用户名密码
    driver.find_element(By.NAME,'username').send_keys('13811033962')
    driver.find_element(By.NAME, 'password').send_keys('123456')
    #输入验证码强制等待

    datu = driver.save_screenshot('datu.png')
    yzmtu = driver.find_element(By.XPATH,'//img[@src="/home/users/verify.html"]')
    location = yzmtu.location
    size = yzmtu.size
    image = Image.open('datu.png')

    left = location['x']
    top = location['y']

    right = left+size['width']
    bottom = top+size['height']
    imagex = image.crop((left*1.5, top*1.5, right*1.5, bottom*1.5))
    imagex.save('imageyzm.png')

    dm = Dama('lr001008  ', '8y0xnq8p', '973035')
    yzmdm = open('imageyzm.png', 'rb').read()
    jieguo = dm.PostPic(yzmdm, 1004)
    print(jieguo)
    result = jieguo['pic_str']
    sleep(2)
    # 输入打码结果到验证码定位
    driver.find_element(By.NAME, 'code').send_keys(result)
    sleep(3)
    #点击登录按钮
    driver.find_element(By.CSS_SELECTOR,'.finish-btn').click()
    cookies = driver.get_cookies()
    #断言欢迎回来
    sleep(5)
    dy2 = driver.find_element(By.XPATH,'/html/body/div[1]/div/div[2]/ul/li[1]/a').text
    print(dy2)
    assert '欢迎回来，13811033962' == dy2



    # 关闭浏览器
    driver.quit()
    # 通过driver.get_cookies()获取当前网站的所有 Cookie 信息（这些 Cookie 包含了登录状态的凭证）
    driver = webdriver.Edge()
    # 打开目标网站
    driver.get('http://10.59.9.14:7003/')
    driver.maximize_window()
    # 添加获取到的 cookie
    for cookie in cookies:
        driver.add_cookie(cookie)

    # 刷新页面，使 cookie 生效，实现免登录
    driver.refresh()

    # 后续可以进行免登录后的操作，比如搜索等
    search = driver.find_element(By.CSS_SELECTOR, '#searchForm > div.header-search > input')
    search.send_keys('音乐耳机')
    sleep(2)
    driver.find_element(By.XPATH, '/html/body/div[2]/div/div/form/div[2]/input').click()

    sleep(5)